package com.chaoyi.processor;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.chaoyi.SpringContext;
import com.chaoyi.service.UserActionService;

public enum UserActionProcessor {
	INSTANCE;
	private final Logger logger = LoggerFactory.getLogger(UserActionProcessor.class);
	private final ThreadPoolExecutor executor;
	
	UserActionProcessor(){
		executor = new ThreadPoolExecutor(1,1,60L,TimeUnit.SECONDS,new LinkedBlockingQueue<>(),new ThreadFactory() {
			private final AtomicInteger count = new AtomicInteger();
			@Override
			public Thread newThread(Runnable r) {
				Thread thread = new Thread(r);
				thread.setName("user-action-thread-"+count.getAndIncrement());
				return thread;
			}
		});
	}
	
	public void start(){
		if(logger.isInfoEnabled())
			logger.info("UserActionProcessor start");
		executor.execute(()->{
			UserActionService userActionService = SpringContext.getContext().getBean(UserActionService.class);
			while(!Thread.interrupted()){
				try{
					userActionService.obtainUserAction();
				}catch(Exception e){
					logger.error("UserActionProcessor error:",e);
				}
			}
		});
	}
	
	public void shutdown(){
		if(logger.isInfoEnabled())
			logger.info("UserActionProcessor stop");
		executor.shutdown();
	}
	
}
